package com.att.device;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import com.android.ddmlib.AndroidDebugBridge;

public class XcatServer {
	private DeviceMonitor monitor;
	private AndroidDebugBridge adb;
	
	public XcatServer(DeviceMonitor monitor) {
		this.monitor = monitor;
		AndroidDebugBridge.init(false);
		adb = AndroidDebugBridge.createBridge();
		while (!adb.hasInitialDeviceList()) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void star(final int port) throws IOException {
		Thread t = new Thread() {
			@Override
			public void run() {
				ServerSocket ss;
				try {
					ss = new ServerSocket(port);
					while (true) {
						Socket s = ss.accept();
						Thread tt = new Thread(new Worker(s));
						tt.start();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		};
		t.start();
	}
	
	class Worker implements Runnable {
		private Socket s;
		private OutputStream out;
		private InputStream in;
		
		public Worker(Socket s) {
			this.s = s;
		}
		
		@Override
		public void run() {
			try {
				out = s.getOutputStream();
				in = s.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				while (true) {
					String cmd = br.readLine();
					if (cmd != null && !"".equals(cmd)) {
						excute(cmd);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
//		private AndroidDebugBridge getADB() throws InterruptedException {
//			AndroidDebugBridge.init(false);
//			AndroidDebugBridge adb = AndroidDebugBridge.createBridge();
//			while (!adb.hasInitialDeviceList()) {
//				Thread.sleep(100);
//			}
//			return adb;
//		}
		
		public void excute(String cmd) throws IOException {
			if ("devices".equals(cmd)) {
				
				String xml = parseXML(monitor.getDevices(adb));
				out.write(xml.getBytes());
				out.flush();
			}
			if ("exit".equals(cmd)) {
				AndroidDebugBridge.terminate();
				s.close();
				System.exit(0);
			}
		}
		
		private String parseXML(List<DeviceInfo> list) {
			StringBuilder sb = new StringBuilder();
			sb.append("<devices>");
			for (DeviceInfo info : list) {
				sb.append("<device>");
				sb.append("<sn>" + info.getSerialNo() + "</sn>");
				sb.append("<model>" + info.getModel() + "</model>");
				sb.append("<brand>" + info.getBrand() + "</brand>");
				sb.append("<screen>" + info.getScreen() + "</screen>");
				sb.append("</device>");
			}
			sb.append("</devices>");
			sb.append("\r\n");
			return sb.toString();
		}
	}
}
